package com.coda.interceptor;

import com.alibaba.fastjson.JSON;
import com.coda.Properties.JwtProperties;
import com.coda.common.Result;
import com.coda.context.BaseContext;
import com.coda.service.TokenService;
import com.coda.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
@Slf4j
@Component
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前请求是否为controller方法
        if (!(handler instanceof HandlerMethod)){
            //不是controller中的方法，静态方法直接放行
            return true;
        }

        try {
            //从请求头中获取token
            String token = request.getHeader(jwtProperties.getTokenName());

            //用户退出登录返回false
//            if (tokenService.isBlackList(token)){
//                return false;
//            }

            //校验jwt令牌
            Claims claims = JwtUtils.parseJWT(jwtProperties.getSecretKey(), token);
            Long id = Long.valueOf( claims.get("Id").toString());

            log.info("当前员工id：{}",id);
            //将员工id存入线程中
            BaseContext.setCurrentId(id);
            //放行
            return true;
        } catch (NumberFormatException e) {
            //jwt校验失败
            Result result = Result.err(Result.CODE_ERR_UNLOGINED, "请先登录");
            //将其转换成json字符串响应前端
            String jsonResult = JSON.toJSONString(result);
            //获取PrintWriter，用于向前端输出数据
            PrintWriter writer = response.getWriter();
            writer.print(jsonResult);
            writer.flush();
            writer.close();
            return false;
        }
    }

    /**
     * 清理用户信息
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.removeCurrentId();
    }
}
